package com.videostreaming.controller;

import com.videostreaming.controller.base.BaseDbController;
import com.gooddies.wiring.annotations.WiringComponent;
import com.videostreaming.data.User;
import com.wiringweb.annotations.Controller;
import com.wiringweb.annotations.UrlBinding;
import com.wiringweb.data.FormData;
import com.wiringweb.http.HttpMethod;
import com.wiringweb.parameterprocessor.annotation.PathVariable;
import com.wiringweb.resolution.PlainTextResolution;
import com.wiringweb.resolution.RedirectResolution;
import com.wiringweb.resolution.Resolution;
import com.wiringweb.resolution.VelocityResolution;
import java.util.UUID;
import org.apache.commons.lang3.RandomStringUtils;

/**
 * @author sad
 */
@Controller
@WiringComponent(singleton = true)
public class RegistrationController extends BaseDbController {

    @UrlBinding("/registration\\.html")
    public Resolution registrationShow() {
        return new VelocityResolution("registration.vm");
    }

    @UrlBinding(httpMethod = HttpMethod.POST, value = "/registration\\.html")
    public Resolution registrationAction(FormData formData) {
        User user = getDb().getUserByEmail((String) formData.getArgument("email"));
        if (user != null) {
            addRequestParameter("errorMessageEmail", "User with such email already exist");
            addRequestParameter("email", formData.getArgument("email"));
            addRequestParameter("fname", formData.getArgument("fname"));
            addRequestParameter("lname", formData.getArgument("lname"));
            return new VelocityResolution("registration.vm");
        }

        user = new User();
        user.setEmail((String) formData.getArgument("email"));
        user.setFirstName((String) formData.getArgument("fname"));
        user.setLastName((String) formData.getArgument("lname"));
        user.setPassword((String) formData.getArgument("password"));
        user.setUserSecretHash(RandomStringUtils.randomAlphanumeric(10));
        getDb().insertUser(user);
        addSessionParameter("loggedUser", user);
        return new RedirectResolution("main.html");
    }

    @UrlBinding(value = "/ifuserexist/(.*?)\\.json")
    public Resolution ifUserExistByEmail(@PathVariable String email) {
        User user = getDb().getUserByEmail(email);
        if (user != null) {
            return new PlainTextResolution("true");
        }
        return new PlainTextResolution("false");
    }
}
